package com.ruoyi.web.task;



import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaModel;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.ruoyi.system.domain.SysSms;
import com.ruoyi.system.service.ISysSmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类TestTask的功能描述:
 * 测试定时任务
 * @auther hxy
 * @date 2017-08-25 09:33:10
 */
@Component("smsTask")
public class SmsTask {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private ISysSmsService smsService;


	private static final String accessKey = "KlAb1pBIna6U3mSn";
	private static final String accessKeySecret = "uCJqihlN6B6KCPTriCR6RtJBHMmYs3";

	public void smsSendTask(String params){
		logger.info("开始执行短信发送服务，参数为：" + params);

		SysSms map =new SysSms(); //只查询启用的发短信会议,未发送的任务，只获取当天的任务比较
		map.setIsEnable(1);
		map.setIsSend(0);
		map.setSendDate(new Date());
		List<SysSms> tasks = smsService.selectSysSmsList(map);
		if( tasks!=null&&!tasks.isEmpty()){
			//先比较时间是否>=设定时间00
			for(SysSms e:tasks){

				if(e.getSendDate().compareTo(new Date())<=0){
					//获取人员短信
					String tels = e.getTel();
					if(tels==null||e.getMeetContext()==null){
						logger.error("发送短信参数异常");
						return;
					}

					String[] meet = e.getMeetContext().split(",");

					//执行发送短信

					String r = smsSend(meet[0], "", "", tels);
					if("ok".equals(r)){
						//标记已发送状态
						e.setIsSend(1);
						smsService.updateSysSms(e);
						System.out.println("执行成功短信发送");
					}else {
						System.out.println("短信发送失败");
						logger.error("短信发送失败");
					}



				}
			}

		}
	}

	public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
		Config config = new Config()
				// 您的AccessKey ID
				.setAccessKeyId(accessKeyId)
				// 您的AccessKey Secret
				.setAccessKeySecret(accessKeySecret);
		// 访问的域名
		config.endpoint = "dysmsapi.aliyuncs.com";
		return new com.aliyun.dysmsapi20170525.Client(config);
	}

	public static String smsSend(String time,String addr,String meet,String tels) {


		try{
			com.aliyun.dysmsapi20170525.Client client = SmsTask.createClient(accessKey, accessKeySecret);
			SendSmsRequest sendSmsRequest = new SendSmsRequest();
			sendSmsRequest.setPhoneNumbers(tels);
			sendSmsRequest.setTemplateCode("SMS_227735730");
			sendSmsRequest.setSignName("山西亨搏数智");
			JSONObject json = new JSONObject();
			json.put("time",time);
			sendSmsRequest.setTemplateParam(json.toJSONString());
			SendSmsResponse resp = client.sendSms(sendSmsRequest);
			com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
			JSONObject result = JSONObject.parseObject(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(resp)));
			if("OK".equals(result.getJSONObject("body").getString("Code"))){
				return "ok";
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return "";
	}

	public static void main(String[] args) {
/*		String template = "【华新销售】您好，%s在%s召开%s，请您准时参加 ！ 综合办公室";
		//初始化clnt,使用单例方式
		YunpianClient clnt = new YunpianClient(apiKey).init();
		String format = String.format(template, "公司定于9月13日（星期一）下午2:30", "西楼2111议室", "第26次中心组学习会、周例会、第24次支委会");
		//发送短信API 【华新销售】您好，2021年8月23日（星期一）下午2:30在公司2111会议室召开周例会、支委会、中心组学习会，请您准时参加! 综合办公室
		Map<String, String> param = clnt.newParam(2);
		param.put(YunpianClient.MOBILE, "18636805545");
		param.put(YunpianClient.TEXT, format);
		Result<SmsBatchSend> r = clnt.sms().batch_send(param);
		logger.info("会议短信发送：",r);
		String hh="【华新销售】您好，%s1在%s2召开%s3，请您准时参加 ！ 综合办公室";
		System.out.println(hh.length());*/
		//smsSend("2021-11-11 16:00","","","18636805545");
		String aa = "{body:{Message:OK, RequestId:C48E6332-1A33-5399-ABD5-FF7E8A2D0BBB, Code:OK, BizId:129404136598216788^0}}";
		JSONObject result = JSONObject.parseObject(com.aliyun.teautil.Common.toJSONString(aa));
		if("ok".equals(result.getJSONObject("body").getString("Code"))){
			System.out.println("ok");
		}
	}

	}


